package com.zyy.weather.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyy.weather.dto.*;
import com.zyy.weather.entity.Menstruation;
import com.zyy.weather.mapper.MenstruationMapper;
import com.zyy.weather.service.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class WeatherServiceImpl implements WeatherService {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private MenstruationMapper menstruationMapper;

    @Override
    public WeatherDTO getWeatherDTO() {
        String weatherUrl = "https://restapi.amap.com/v3/weather/weatherInfo?key=5c803f6a7637de72eb293dc19e1a906a&city=410621";
        ResponseEntity<String> entity = restTemplate.getForEntity(weatherUrl, String.class);
        WeatherDTO weatherDTO = JSONObject.parseObject(entity.getBody()).getJSONArray("lives").getObject(0, WeatherDTO.class);
        return weatherDTO;
    }

    public SoJsonDTO getSoWeather() {
        String url = "http://t.weather.itboy.net/api/weather/city/101181202";
        SoJsonDTO soJsonDTO = restTemplate.getForObject(url, SoJsonDTO.class);
        return soJsonDTO;
    }

    @Override
    public String getOneSentence() {
        String url = "https://api.vvhan.com/api/text/love";
        ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
        String sentence = entity.getBody().toString();
        System.out.println(sentence);
        return sentence;
    }

    /**
     * 获取月经
     *
     * @return
     */
    @Override
    public String getMenstruation() {
        /**
         * 0、当前时间-上次结束时间 = 计算天数
         * 1、读取最新的大姨妈记录
         * 2、最新记录的开始时间+周期=下次大姨妈时间
         * 3、周期-姨妈时间/3中间部分为排卵期
         * 4、大姨妈推迟如何记录？？？（设置标志位如果未开始则标志位不改变。）
         * 5、当前时间-结束时间
         */
        String str = new String();
        QueryWrapper<Menstruation> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        List<Menstruation> menstruationList = menstruationMapper.selectList(wrapper);
        Menstruation menstruation = menstruationList.get(0);
        //现在时间距离结束时间
        long day = (new Date().getTime() - menstruation.getEndDate().getTime()) / (1000 * 3600 * 24);
        //大姨妈区间时间
        long interval = (menstruation.getEndDate().getTime() - menstruation.getStartDate().getTime()) / (1000 * 3600 * 24);
        long stage = ((menstruation.getCycle() - interval - 1) / 3) + 1;
        if (day < stage) {
            //第一阶段安全期
            str = "大姨妈已经过去" + day + "天了，可以放开的的吃喝玩乐了。";
        } else if (day < 2 * stage) {
            //排卵期
            str = "排卵期的第" + (2 * stage - day) + "天，正是怀孕的好时机，可惜咱们还没结婚。哈哈哈";
        } else if (day < 3 * stage) {
            //二阶段安全期
            str = "距离下次姨妈还有" + (3 * stage - day) + "天，注意饮食哟，不要吃凉的辣的，早睡早起保持好心情！";
        } else {
            //姨妈推迟
            str = "大姨妈迟到了" + (day - 3 * stage) + "天了，不要慌，肯定是这个月刘智超气了你了，我替你教训他。";
        }

        return str;
    }


    /**
     * 加工要返回的字符串
     *
     * @param soWeather
     * @param oneSentence
     * @return
     */
    @Override
    public String getString(SoJsonDTO soWeather, String oneSentence, String menstruation) {
        CityInfo cityInfo = soWeather.getCityInfo();
        WeatherData data = soWeather.getData();
        ArrayList<forecast> forecast = soWeather.getData().getForecast();
        String s = new String("宝贝早上好，今天" + cityInfo.getCity() + "天气" + forecast.get(0).getType() + "," + forecast.get(0).getNotice() + "\n\n"
                + "我们已经相恋" + getDay("2021-07-24 06:00:00") + "天\n\n"
                + menstruation + "\n\n"
                + "今天最" + forecast.get(0).getHigh() + "最" + forecast.get(0).getLow() + "\n\n"
                + "空气质量" + data.getQuality() + "\n\n"
                + "湿度：" + data.getShidu() + "\n\n"
                + "PM2.5：" + data.getPm25() + "\n\n"
                + "今天" + forecast.get(0).getFx() + "," + forecast.get(0).getFl() + "\n\n"
                + oneSentence

        );
        return s;
    }

    public static Long getDay(String date) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long days = null;
        try {
            Date currentTime = dateFormat.parse(dateFormat.format(new Date()));//现在系统当前时间
            Date pastTime = dateFormat.parse(date);//过去时间
            long diff = currentTime.getTime() - pastTime.getTime();
            days = diff / (1000 * 60 * 60 * 24);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }
}
